package org.cloudlab.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cloudlab.bean.SysUser;
import org.cloudlab.common.CommonConst;
import org.cloudlab.common.LoginUser;
import org.cloudlab.controller.UserController;
import org.cloudlab.mapper.SysUserMapper;
import org.cloudlab.service.ISysUserService;
import org.cloudlab.service.IUserService;
import org.cloudlab.utils.JwtTokenUtil;
import org.cloudlab.utils.PasswordEncoderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户登录的服务层实现类
 *
 * @author Liu Yicong
 * @date 2023/9/5
 */
@Service
public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements IUserService {

	/**
	 * @see UserController
	 */
	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Override
	public String login(SysUser user) {
		//使用AuthenticationManager进行用户认证, 将用户名和密码封装为一个token对象
		UsernamePasswordAuthenticationToken authenticationToken =
				new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
		Authentication authenticate = authenticationManager.authenticate(authenticationToken);
		//如果认证没有通过
		if (Objects.isNull(authenticate)) {
			throw new RuntimeException("登录失败");
		}
		//如果认证通过则使用userid生成一个jwt, 将JWT存入ResponseResult返回
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
		//将完整的用户信息存入Redis, 使用username作为key
		return jwtTokenUtil.generatorToken(loginUser);
	}

	@Override
	public void register(SysUser user) {
		// 不可为空
		boolean isNull = Objects.isNull(user.getUserName()) || Objects.isNull(user.getNickName()) || Objects.isNull(user.getPassword());
		if (isNull) {
			throw new RuntimeException("用户名/昵称/密码不能为空");
		}
		Long same = sysUserService.lambdaQuery().eq(SysUser::getUserName, user.getUserName()).count();
		if (same > 0) {
			throw new RuntimeException("用户名已经被占用");
		}
		String code = PasswordEncoderUtil.encodePassword(user.getPassword());
		user.setPassword(code);
		user.setRole(CommonConst.COMMON_ROLE);
		sysUserService.save(user);
	}

	@Override
	public void logout() {
		//获取SecurityContextHolder中的用户Id

	}


}
